package com.chigga.application.hanlder.login.exception;

import com.chigga.common.constants.HttpStatusConstant;
import com.chigga.common.core.domain.ResponseResult;
import com.chigga.common.utils.JSON;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 捕捉Spring security filter chain 中抛出的未知异常
 *
 * @author DefChigga
 */
public class CustomSecurityExceptionHandler extends OncePerRequestFilter {

    public static final Logger logger = LoggerFactory.getLogger(
            CustomSecurityExceptionHandler.class);

    @Override
    public void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (AuthenticationException | AccessDeniedException e) {
            // 设置状态码，响应/编码类型
            response.setStatus(HttpStatusConstant.FORBIDDEN);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            // 把对象转为 json 字符串
            PrintWriter writer = response.getWriter();
            writer.print(JSON.stringify(ResponseResult.failure(HttpStatusConstant.FORBIDDEN, e.getMessage())));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            // 设置状态码，响应/编码类型
            response.setStatus(HttpStatusConstant.FORBIDDEN);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            // 把对象转为 json 字符串
            PrintWriter writer = response.getWriter();
            writer.print(JSON.stringify(ResponseResult.failure(e.getMessage())));
            writer.flush();
            writer.close();
        }
    }
}
